<?php
namespace app\user\controller;
use app\user\model\StoreUser as StoreUserModel;
use app\user\model\WebOrder as WebOrderModel;
use app\user\model\WebSet as WebSetModel;

/**
 * 钱包余额管理
 */
class Wallet extends Controller
{	
	/**
     * 用户钱包
     */
    public function index()
    {
		$store = StoreUserModel::detail($this->store_user_id);
        if (!$this->request->isAjax()) {
			$this->assign('wallet',$store['wallet']);
			return $this->fetch('index');
        }
		$model = new WebOrderModel;
		$pay = $this->postData('pay');
		// 创建订单
		if($model->add([
            'pay_price' => $pay['money'],
            'purpose' => '扫码充值',
            'affair_id' => $this->store_user_id,
            'agent_id' => $this->agent_id,
            'store_user_id' => $this->store_user_id
        ])) {
			return $this->renderSuccess('二维码生成中...', url('wallet/recharge',[
                'order_no'=>$model['order_no'],
                'money'=>$pay['money']
            ]));
        }
        $error = $model->getError() ?: '订单创建失败';
        return $this->renderError($error);
    }

    /**
     * 余额提现
     */
    public function cash()
    {
        $store = StoreUserModel::detail($this->store_user_id);
        if (!$this->request->isAjax()) {
            $this->assign('wallet',$store['wallet']);
            return $this->fetch('cash');
        }
        $model = new WebOrderModel;
        $pay = $this->postData('pay');
        if($store['wallet'] < $pay['money']){
           return $this->renderError('提现金额不可大于账户余额'); 
        }
        $values = WebSet::getItem('payment');
        if($values['wx']['cash_mode'] == 'fixed' AND $values['wx']['cash_fee'] > $pay['money']){
            return $this->renderError('不可提现，提现金额要大于￥'.$values['wx']['cash_fee'].'元'); 
        }
        // 创建订单
        if($model->add([
            'pay_price' => $pay['money'],
            'order_type' => 40,
            'purpose' => '用户提现',
            'affair_id' => $this->store_user_id,
            'agent_id' => $this->agent_id,
            'store_user_id' => $this->store_user_id
        ])) {
            return $this->renderSuccess('提交成功', url('wallet/index'));
        }
        $error = $model->getError() ?: '订单创建失败';
        return $this->renderError($error);
    }
	
	/**
     * 商户充值
     */
    public function recharge($order_no,$money)
    {
		$code_url = wxPay([],$order_no, '', $money, 'native');
		$this->assign('money',$money);
		$this->assign('code_url',$code_url);
		return $this->fetch('recharge');
    }

	/**
     * 支付流水
     */
    public function log()
    {
        $model = new WebOrderModel;
        $list = $model->getList('',$this->store_user_id);
        return $this->fetch('log', compact('list'));
    }
}
